import { Style, Fill, Stroke, Icon,Circle as CircleStyle } from "ol/style";
import polyline from '@mapbox/polyline';
import Feature from 'ol/Feature';
import {Point } from 'ol/geom';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import type { 
    Coordinate,
  } from '@/types/map';
import Select from 'ol/interaction/Select';

export const  getImageStyle = (name:string) => {
    return new Style({
        image: new Icon({
            src: require(`@/assets/image/${name}.png`),
            anchor: [0.5, 0.5],
            scale: 1.2
        }),
        zIndex: 100
    });
}

export const  getStyle = (stroke:string,fill:string, storkeWidth?:number, index?:number) => {
    return new Style({
        stroke: new Stroke({
            color: stroke,
            width: storkeWidth || 2
        }),
        fill: new Fill({
            color: fill,
        }),
        zIndex: index || 100
    });
}

export const getCircleStyle = (radius?:number,fillColor?:string) =>{
    return new Style({
        image: new CircleStyle({
            radius: radius||5,
            fill: new Fill({
                color: fillColor||'Crimson',
            })
        })
    });
}

export const BASE_RESOURCE_URL = (vectorId) => {
    // 拼接环境变量中的基础路径和API基础路径，加上文件资源的相对路径和文件ID
    return `${process.env.VUE_APP_DISK}${process.env.VUE_APP_BASE_API}/resources/file/${vectorId}`;
}

export const  getLayerByName = (layers ,name: string)  => {
    return layers.find(l => l.name === name)?.layer;
}

// 解码函数
export function decodeGraphHopperPolyline(encoded: string, multiplier: number): Coordinate[] {
    try {
        const decoded = polyline.decode(encoded);
        return decoded.map(coord => [
            coord[0] / multiplier,
            coord[1] / multiplier
        ]) as Coordinate[];
    } catch (error) {
        console.error('Polyline解码失败:', error);
        return [];
    }
}

export const zoomToFeature =(context,feature: any) => {
    const geometry = feature.geometry;
    if (geometry) {
        const view = context.map?.getView();
        view?.fit(geometry.getExtent(), {
            padding: [50, 50, 50, 50],
            duration: 1000,
            maxZoom: 14
        });
    }
}

export function getStartPoint(item: any): number[] | null {
    // 示例：获取当前地图中心点
    return item.location.split(',');
}

   // 清理路径
export function  clearRoutes(context, name) {
    const routeLayer: any = getLayerByName(context,name);
    routeLayer.getSource()?.clear();
}


    // 获取要素坐标
export function  getFeatureCoordinates(feature: Feature): number[] | null {
    const geometry = feature.getGeometry();
    if (geometry instanceof Point) {
        return geometry.getCoordinates();
    }
    return null;
}

    export function createBaseLayer(mapTypes, currentMapType: string) {
        const config = mapTypes.find(m => m.type === currentMapType);
        if (!config) return;

        return new TileLayer({
            source: new XYZ({
                url: config.url,
                attributions: config.attribution,
                tileSize: 256,
                crossOrigin: 'anonymous'
            })
        });
    }

export function initSelectInteraction(context: any, layerName:any) {
    context.selectInteraction = new Select({
        layers: [getLayerByName(context, layerName)],
        filter: (feature) => {
            return feature.get('type') === 'marker'; // 只选择类型为marker的要素
        },
        style: getImageStyle('location-selected')
    });

    context.map?.addInteraction(context.selectInteraction);

    // 监听选择事件
    context.selectInteraction.on('select', (e: any) => {
        if (e.selected.length > 0) {
            context.selectedFeature = e.selected[0];
            context.showFeatureInfo(context.selectedFeature);
        } else {
            context.selectedFeature = null;
        }
    });
}

export function toLocation(context, position: any, zoom?:number,duration?:number) {
    if (position && position.length === 2) {
        context.map.setCenter(position);
        context.map.setZoom(zoom || 14);
        // context.map?.getView().animate({
        //     center: position, // 新的中心坐标
        //     zoom: zoom || 14,        // 新的缩放级别
        //     duration: duration || 3000   // 动画持续时间（毫秒）
        // });
    }
}

export function findFeaturesInGeometry(geometry,targetSource) {
  const featuresInRange:any = [];

  targetSource.getFeatures().forEach((feature: any) => {
    if (feature.getGeometry().getType() === 'Point') {
       if(geometry.intersectsCoordinate(feature.getGeometry().getCoordinates())){
        featuresInRange.push(feature);
       }
    }
  });
  // 高亮或处理这些要素
  highlightFeatures(featuresInRange);
  return featuresInRange;
}

export function highlightFeatures(features) {
  features.forEach(feature => {
    feature.setStyle(getStyle('rgba(255,0,0,0.5)', 'darkgreen'));
  });
}

export function  getDefaultOverlayName(overlay: any): string {
    const className = overlay.CLASS_NAME;
    
    // Use a mapping object for better maintainability 
    const nameMap = {
        'Overlay.Circle': () => {
            const center = overlay.getCenter(); 
            const radius = Math.round(overlay.getRadius())  / 1000;
            return `中心点: ${center.lng},${center.lat}  半径：${radius}km 圆形区域`;
        },
        'Overlay.Polygon': '多边形区域',
        'Overlay.Polyline': '折线',
        'Overlay.Rectangle': '矩形区域',
        'AMap.Marker': () => {
            const position = overlay.getPosition(); 
            return `坐标：${position.lng},${position.lat}  标记点`;
        }
    };
    
    // Return the appropriate name or default 
    const nameResolver = nameMap[className];
    return typeof nameResolver === 'function' 
        ? nameResolver() 
        : nameResolver || '圆形区域'; // Default fallback 
}

const typeMap: Record<string, string> = {
    'AMap.Marker': '标记点',
    'Overlay.Circle': '圆形',
    'Overlay.Polygon': '多边形',
    'Overlay.Rectangle': '矩形区域',
    'Overlay.Polyline': '折线'
};

export function  getTypeName(type: string) {
    return typeMap[type] || type;
}

const classMap = {
      'AMap.Marker': 'marker-tag',
      'Overlay.Circle': 'circle-tag',
      'Overlay.Polygon': 'polygon-tag',
      'AMap.Polygon': 'polygon-tag',
      'Overlay.Rectangle': 'rectangle-tag',
      'Overlay.Polyline': 'polyline-tag'
    };

export function getTypeTagClass(type) {
    return classMap[type] || '';
}


export function formatRadius(radius: number): string {
    return radius > 1000
      ? `${(radius / 1000).toFixed(2)} km`
      : `${radius.toFixed(2)} m`;
  }

export function  formatArea(area: number): string {
    return area > 1000000
      ? `${(area / 1000000).toFixed(2)} km²`
      : `${area.toFixed(2)} m²`;
  }

export function  formatLength(length: number): string {
    return length > 1000
      ? `${(length / 1000).toFixed(2)} km`
      : `${length.toFixed(2)} m`;
  }

  // 计算圆形面积
export function   calculateCircleArea(radius: number): number {
    return Math.PI * Math.pow(radius, 2);
  }

  
 export function  formatPosition(pos: any): string {
    return pos ? `${pos.lng.toFixed(6)}, ${pos.lat.toFixed(6)}` : '-';
  }

declare const AMap: any;
export function  getArea(path: any[]): number {
   
    return Math.round(AMap.GeometryUtil.ringArea(path)); 
}

export function  calculatePolygonCenter(path: any[]): any {
  
  let totalArea = 0;
  let centerX = 0;
  let centerY = 0;
  
  for (let i = 0, len = path.length; i < len; i++) {
    const { lng: x1, lat: y1 } = path[i];
    const { lng: x2, lat: y2 } = path[(i + 1) % len];
  
    const areaPart = (x1 * y2 - x2 * y1);

    totalArea += areaPart;
    
    centerX += (x1 + x2) * areaPart;
    centerY += (y1 + y2) * areaPart;
  }
  
  totalArea /= 2;
  centerX /= (6 * totalArea);
  centerY /= (6 * totalArea);
  
  return new AMap.LngLat(centerX, centerY);
}


